<?php

/*
*/

class Stock_advices_details_model extends CI_Model
{

	static $TABLE;
	public $error;

	function __construct()
	{
		parent::__construct();
		//选择数据库
		$this->load->library('test_database');
		$this->test_database->test();
		$this->load->database($this->test_database->get_db());
		//载入类库
		$this->load->library('form_validation');
		//载入模型
		$this->load->model('Inbound_Type_model');
		$this->load->model('Outbound_Type_model');
		//初始化模型
		$this->Inbound_Type_model->init();
		$this->Outbound_Type_model->init();
		//载入本地语言文件
		$this->lang->load('form_validation','chinese');
		//初始化数据
		$this->TABLE = 'stock_advices_details';		//数据表
		$this->TEMP_TABLE = 'temp_' . $this->TABLE;	//临时数据表
		$this->error = FALSE;		//错误
		$this->mode = FALSE;		//处理模式
	}

	/***
	For private function here
	***/

	/***
	For public function here
	***/

	public function create_detail($stock_advice_id, $stock_details, $view)
	{
		$this->load->model('stock_detail_model');
		$this->load->model('stock_advices_model');
		$this->load->model('stock_advice_stock_model');
		$this->load->model('sub_goods_model');

		//获得库类型
		$this->Inbound_Type_model->get_all('ID_FLG');
		$this->Outbound_Type_model->get_all('ID_FLG');

		//获取上个周期的结算数据
		$prev_advice_details = $this->get_advice_details($stock_advice_id, -1);
		if (-1 === $prev_advice_details)
		{
			return $this->error = '无法创建结算表，请稍候再试或联系管理员。';
		}

		$sub_goods_order = array();	//初始话货物订单信息
		$sub_goods_stock = array();	//初始化货物库存信息
		//用上个周期的数据初始化这个周期的数据
		if (!empty($prev_advice_details))
		{
			foreach ($prev_advice_details as $detail)
			{
				//上一个周期的结算数据归类成为进货属性，以便计算成本
				$sub_goods_order[$detail->sub_goods_id]['sub_goods_id'] = $detail->sub_goods_id;
				$sub_goods_order[$detail->sub_goods_id]['order_quantity'] = array_sum($detail->quantity);
				$sub_goods_order[$detail->sub_goods_id]['value'] = $sub_goods_order[$detail->sub_goods_id]['order_quantity'] * $detail->sub_goods_price;
				$sub_goods_order[$detail->sub_goods_id]['price'] = $detail->sub_goods_price;
<<<<<<< HEAD

				//记录子货物各个仓库的数量
				foreach ($detail->quantity as $id=>$quantity)
				{
					$sub_goods_stock[$detail->sub_goods_id]['quantities'][$id] = $quantity;
				}
=======
				//记录子货物各个仓库的数量
				$sub_goods_stock[$detail->sub_goods_id]['quantities'] = $detail->quantity;
>>>>>>> ff5f7ef6de592146b376adc8ed0c004b06507151
			}
		}

		$advice_id = $this->stock_advices_model->get_advice_id($stock_advice_id);	//关联的结算单ID
		$order_cost = 0;	//订单理论总值
		$goods_value = 0;	//订单理论总值
		foreach ($stock_details as $key=>$detail)
		{
			//库存详情基本数据
			$stock_details_id = $detail->stock_details_id;	//库存详情ID
			$del_flg = $detail->del_flg;	//删除标识符
			$id = $detail->sub_goods_id;	//详情中的子货物ID
			$quantity = $detail->quantity;	//库存数量
			$price = $detail->price;		//进货价格
			$store_id = $detail->store_id;	//仓库ID
			$s_type = $detail->stock_type;	//出库或入库

			//设置结算标识符
			if (!$this->stock_detail_model->set_balanced($stock_details_id))
			{
				$this->error = $this->stock_detail_model->error;
				return FALSE;
			}

			//关联结算单ID
			if (!$this->stock_detail_model->relate_advice($stock_details_id, $advice_id))
			{
				$this->error = $this->stock_detail_model->error;
				return FALSE;
			}

			//收集计算库存所需要的数据
			//判断删除标识符
			if (0 == $del_flg)
			{
				//判断出入库类型为数量复制正负
				if ('inbound' == $s_type)
				{
					$quantity = $quantity;
				}
				else if ('outbound' == $s_type)
				{
					$quantity = -$quantity;
				}

				//累积各个仓库子货物的数量
				if (isset($sub_goods_stock[$id]['quantities'][$store_id]))
				{
					$sub_goods_stock[$id]['quantities'][$store_id] += $quantity;
				}
				else
				{
					$sub_goods_stock[$id]['quantities'][$store_id] = $quantity;
				}

				//如果是进货库存单，累积计算子货物进货总值
				if ('inbound' == $s_type && $this->Inbound_Type_model->is_order($detail->bound_type_id))
				{
					if (isset($sub_goods_order[$id]['order_quantity']))
					{
						$sub_goods_order[$id]['order_quantity'] += $quantity;
						$sub_goods_order[$id]['value'] += $quantity * $price;
					}
					else
					{
						$sub_goods_order[$id]['sub_goods_id'] = $id;
						$sub_goods_order[$id]['order_quantity'] = $quantity;
						$sub_goods_order[$id]['value'] = $quantity * $price;
					}
					//累积子货物进货理论费用
					$order_cost += $quantity * $price;
				}
			}
		}

		//计算单个子货物的成本并更新数据报表
		$sub_goods_price = array();		//初始化子货物成本价格
		$main_goods = array();			//初始化主货物数组
		$sub_goods = $this->sub_goods_model->get_all();

		//可优化，有重复查询数据
		foreach ($sub_goods as $goods)
		{
			$data = array(
				'stock_advice_id'	=> $stock_advice_id,
				'sub_goods_id'		=> $goods->sub_goods_id,
				'create_date'		=> time()
				);

			if ($goods_info = $this->sub_goods_model->get_goods_info($goods->sub_goods_id))
			{
				//添加需要插入的数据
				$data['attribute'] = $goods_info['sub_goods']['attribute'];
				$data['number'] = $goods_info['sub_goods']['number'];
				$data['search_code'] = $goods_info['sub_goods']['search_code'];
				$data['main_goods_id'] = $goods_info['main_goods']['main_goods_id'];
				$data['name'] = $goods_info['main_goods']['name'];

				//判断插入图片
				if ($goods_info['sub_goods']['image'])
				{
					$data['image'] = $goods_info['sub_goods']['image'];
				}
				else if ($goods_info['main_goods']['taobao_info']['image'])
				{
					$data['image'] = $goods_info['main_goods']['taobao_info']['image'];
				}
				else
				{
					$data['image'] = '';
				}
				unset($goods_info);
			}
			else
			{
				$this->error = $this->sub_goods_model->error;
				return FALSE;
			}

			if (isset($sub_goods_order[$goods->sub_goods_id]))
			{
				if (0 != $sub_goods_order[$goods->sub_goods_id]['order_quantity'])
				{
					$data['sub_goods_price'] = round($sub_goods_order[$goods->sub_goods_id]['value'] / $sub_goods_order[$goods->sub_goods_id]['order_quantity'], 3);
				}
				else
				{
					$data['sub_goods_price'] = $sub_goods_order[$goods->sub_goods_id]['price'];
				}
			}
			else
			{
				$data['sub_goods_price'] = 0;
			}

			if ($this->db->insert($this->TABLE, $data))
			{
				//重新赋值成本价再计算当前货物总值
				$sub_goods_price[$goods->sub_goods_id] = $data['sub_goods_price'];
			}
			else
			{
				$this->error = 'CANNOT_CREATE_SUB_GOODS_PRICE';
				return FALSE;
			}
			unset($data);	//销毁$data
		}

		//更新结算的所有库存详情历史价格信息，非进货单
		//$stock_details : 所有结算的库存单详情
		//$sub_goods_price : 所有已有成本价的子货物
		foreach ($stock_details as $detail)
		{
			if (isset($sub_goods_price[$detail->sub_goods_id]) && !($this->Inbound_Type_model->is_order($detail->bound_type_id) && 'inbound' == $detail->stock_type))
			{
				if (!$this->stock_detail_model->set_balance_price($detail->stock_details_id, $sub_goods_price[$detail->sub_goods_id]))
				{
					$this->error = $this->stock_detail_model->error;
					return FALSE;
				}
				//var_dump($sub_goods_price[$detail->sub_goods_id]);
			}
		}

		//计算货物当前总值$goods_value 以及 货物总数$goods_quantity
		$goods_quantity = 0;
		foreach ($sub_goods_stock as $sub_goods_id=>$stock_info)
		{
			//如果计算出有成本价，则累加货物价值
			if (isset($sub_goods_price[$sub_goods_id]))
			{
				$goods_value += array_sum($stock_info['quantities']) * $sub_goods_price[$sub_goods_id];
			}
			$goods_quantity += array_sum($stock_info['quantities']);
		}

		//创建结算的具体库存信息
		$this->stock_advice_stock_model->create_stock($stock_advice_id, $sub_goods_stock);
		if ($this->error = $this->stock_advice_stock_model->error)
		{
			return FALSE;
		}

		//更新货物总数
		if (!$this->stock_advices_model->update_row('goods_quantity', $goods_quantity, $stock_advice_id))
		{		
			$this->error = __CLASS__ . '::' . __FUNCTION__ . ' ON ' . __LINE__ . ':' . 'CANNOT UPDATE ORDER COST';
			return FALSE;
		}

		//更新进货应付货款额度
		if (!$this->stock_advices_model->update_row('order_cost', $order_cost, $stock_advice_id))
		{		
			$this->error = __CLASS__ . '::' . __FUNCTION__ . ' ON ' . __LINE__ . ':' . 'CANNOT UPDATE ORDER COST';
			return FALSE;
		}

		//更新货物总值
		if (!$this->stock_advices_model->update_row('goods_value', $goods_value, $stock_advice_id))
		{
			$this->error = __CLASS__ . '::' . __FUNCTION__ . ' ON ' . __LINE__ . ':' . 'CANNOT UPDATE ORDER COST';
			return FALSE;
		}

	}

	//获取一个周期或上一个周期或下一个周期的所有结算数据
	public function get_advice_details($stock_advice_id, $offset=FALSE)
	{
		if ($offset)
		{
			$stock_advice_id = $this->stock_advices_model->get_offset_advice_id($stock_advice_id, $offset);
			//获取错误返回值为-1，表单为空获取值为0
			if ($stock_advice_id < 1)
			{
				return array();
			}
		}

		$this->db->where('stock_advice_id = '.$stock_advice_id);
		$query = $this->db->get($this->TABLE);
		if ($query->num_rows() > 0)
		{
			$advice_details = $query->result();

			//取得结算货物的库存信息并重构数据
			$advice_stocks = $this->stock_advice_stock_model->get_stock($stock_advice_id, TRUE);

			foreach ($advice_details as $key=>$stock)
			{
				$advice_details[$key]->quantity = $advice_stocks[$stock->sub_goods_id];
			}
			return $advice_details;
		}
		else
		{
			return array();
		}
	}

	//获得单条最新的记录
	public function get_single_detail($type, $id, $return)
	{
		$this->db->where($type, $id);
		$this->db->order_by('stock_adv_detail_id DESC');
		$this->db->limit(1);
		$query = $this->db->get($this->TABLE);
		if ($query->num_rows() > 0)
		{
			$result = $query->result();
			if ('PRICE' === $return)
			{
				return $result[0]->sub_goods_price;
			}
			else
			{
				return $result[0];
			}
		}
		else
		{
			return array();
		}
	}

	//获得单条成本记录
	public function get_single_price($stock_advice_id, $sub_goods_id)
	{
		$this->db->where('stock_advice_id', $stock_advice_id);
		$this->db->where('sub_goods_id', $sub_goods_id);
		$this->db->limit(1);
		$result = $this->db->get($this->TABLE)->row();
		if (!empty($result))
		{
			return $result->sub_goods_price;
		}
		else
		{
			return 0;
		}
	}

}